package com.xatz.scanner

import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.TextView
import androidx.fragment.app.Fragment
import androidx.recyclerview.widget.RecyclerView
import com.xatz.scanner.bean.DataTable
import com.xatz.scanner.databinding.FragmentSelectPageBinding
import timber.log.Timber

/**
 * author: tdq
 * date: 2021/7/20
 * description: 查询页
 */
class SelectPageFragment : Fragment() {

    private lateinit var mAdapter: MySelectAdapter

    private lateinit var mBinding: FragmentSelectPageBinding

    private val mList = mutableListOf<DataTable>()

    override fun onCreateView(
        inflater: LayoutInflater,
        container: ViewGroup?,
        savedInstanceState: Bundle?
    ): View {
        mBinding = FragmentSelectPageBinding.inflate(inflater, container, false)
        return mBinding.root
    }

    override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
        mAdapter = MySelectAdapter(mList)
        mBinding.rvDetails.adapter = mAdapter
    }

    fun onScannerResult(data: DataTable?) {
        mList.clear()
        data?.run {
            requireActivity().runOnUiThread {
                mBinding.tvBillNum.text = C_DELIVERY
                mBinding.tvCalNum.text = C_PLATE_NUMBER
                mBinding.tvWeightTwo.text = N_PLAN_WGT
                mList.add(this)
                mAdapter.notifyDataSetChanged()
            }
        }
    }

    fun clearData(){
        mBinding.tvBillNum.text = ""
        mBinding.tvCalNum.text = ""
        mBinding.tvWeightTwo.text = ""
        mList.clear()
        mAdapter.notifyDataSetChanged()
    }
}

class MySelectAdapter(private val mList: MutableList<DataTable>) :
    RecyclerView.Adapter<MySelectViewHolder>() {
    override fun onCreateViewHolder(
        parent: ViewGroup,
        viewType: Int
    ): MySelectViewHolder {
        return MySelectViewHolder(
            LayoutInflater.from(parent.context)
                .inflate(R.layout.item_details, parent, false)
        )
    }

    override fun onBindViewHolder(holder: MySelectViewHolder, position: Int) {
        try {
            holder.tvNum?.text = mList[position].C_MAT_DESC
            holder.tvType?.text = mList[position].N_PLAN_WGT
            holder.tvWeight?.text = mList[position].C_MAT_CODE
        } catch (e: Exception) {
            Timber.e(e)
        }

    }

    override fun getItemCount(): Int {
        return mList.size
    }
}

class MySelectViewHolder(itemView: View) : RecyclerView.ViewHolder(itemView) {
    var tvNum: TextView? = null
    var tvType: TextView? = null
    var tvWeight: TextView? = null

    init {
        tvNum = itemView.findViewById(R.id.tvNum)
        tvType = itemView.findViewById(R.id.tvType)
        tvWeight = itemView.findViewById(R.id.tvWeight)
    }
}